<?php

declare(strict_types=1);

namespace App\Controller\Home\Drp;

use App\Constants\ErrorCode;
use App\Model\ChargeDetail;
use App\Model\ChargeOption;
use App\Model\Distributors;
use App\Model\Station;
use Exception;
use Hyperf\Redis\Redis;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;

;

use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use App\Controller\AbstractController;

/**
 * 充电控制器
 */
class ChargeController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected ChargeOption $chargeOption;
    #[Inject]
    protected Station $station;
    #[Inject]
    protected ChargeDetail $chargeDetail;

    #[Inject]
    protected Distributors $distributors;


    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }


    /**
     * 获取列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request): ResponseInterface
    {
        $page = $request->inputs(['page', 'limit', 'keyword', 'is_autoload', 'mode']);
        if(!$page['page']){
            $page['page'] = 1;
        }
        if(!$page['limit']){
            $page['limit'] = 10;
        }
        $info = $this->distributors->getInfo($request);
        if (!$info) {
            return $this->error(code: '400', msg: '登录态失效 请重新登录');
        }
        try {
            $model = $this->chargeOption->where(function ($query) use ($page, $info) {
                if (array_key_exists('keyword', $page) && $page['keyword']) {
                    $query->where('name', 'like', '%' . $page['keyword'] . '%');
                }
                if ($page['is_autoload'] != '') {
                    $query->where('is_autoload', $page['is_autoload']);
                }
                if ($page['mode'] == 'pt') {
                    $query->where('distributor_id', '=', 0);
                } else {
                    $query->where('distributor_id', '=', $info['id']);
                }
                $query->where('is_del', 1);
            });

            $data['total'] = $model->count();
            $data['list'] = $model
                ->with('time_children', 'power_children', 'service_children')
                ->orderBy('sort', 'desc')
                ->offset(($page['page'] - 1) * $page['limit'])
                ->limit($page['limit'])
                ->get()->toArray();
            return $this->success($data);
        } catch (\Exception $e) {
            return $this->error(1001, $e->getMessage());
        }
    }


    public function getAll(RequestInterface $request){
        $info = $this->distributors->getInfo($request);
        $data = $this->chargeOption
            ->where(function ($query) use ($info) {
                $query->where('distributor_id', $info['id'])
                    ->orWhere('distributor_id', 0);
            })
            ->where('is_del', 1)
            ->orderBy('distributor_id','asc')
            ->get();
        return $this->success($data);
    }


    /**
     * 创建/编辑
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request): ResponseInterface
    {
        $params = $request->inputs(['id', 'type', 'service_type', 'service_fee', 'min_price', 'service_children',
            'name', 'is_autoload', 'fee', 'power_children', 'time_children', 'elec_price']);
        if (!$params['name']) {
            return $this->error(code: 1002, msg: '套餐名称不能为空');
        }
        $info = $this->distributors->getInfo($request);
        $params['distributor_id'] = $info['id'];
        Db::beginTransaction();
        try {
            $save['is_autoload'] = $params['is_autoload'];
            $save['name'] = $params['name'];
            $save['distributor_id'] = $params['distributor_id'];
            $save['min_price'] = $params['min_price'];
            $save['fee'] = $params['fee'];
            if ($params['type'] == ChargeDetail::SERVICE) {
                $save['service_type'] = $params['service_type'];
                $save['service_fee'] = $params['service_fee'];
                $save['elec_price'] = $params['elec_price'];
            }
            $save['type'] = $params['type'];
            $option = ChargeOption::create($save);
            $params['id'] = $option->id;
            if ($params['type'] == ChargeDetail::SERVICE && $params['service_type'] == 2) {
                if (isset($params['service_children'])) {
                    $params['service_children'] = json_decode($params['service_children'], true);
                    foreach ($params['service_children'] as $k => $v) {
                        $save = [];
                        $save['fee'] = $v['fee'];
                        $save['min_power'] = $v['min_power'];
                        $save['max_power'] = $v['max_power'];
                        $save['charge_option_id'] = $params['id'];
                        $save['type'] = ChargeDetail::SERVICE;
                        ChargeDetail::create($save);
                    }
                }
            }
            if (isset($params['power_children'])) {
                $params['power_children'] = json_decode($params['power_children'], true);
                foreach ($params['power_children'] as $k => $v) {
                    if (isset($v['minutes']) && isset($v['min_power']) && isset($v['max_power'])) {
                        $save = [];
                        $save['minutes'] = $v['minutes'];
                        $save['min_power'] = $v['min_power'];
                        $save['max_power'] = $v['max_power'];
                        $save['charge_option_id'] = $params['id'];
                        $save['type'] = ChargeDetail::POWER;
                        ChargeDetail::create($save);
                    }
                }
            }
            if (isset($params['time_children'])) {
                $params['time_children'] = json_decode($params['time_children'], true);
                foreach ($params['time_children'] as $k => $v) {
                    if (isset($v['fee'])) {
                        $save = [];
                        $save['type'] = ChargeDetail::FEE;
                        $save['fee'] = $v['fee'];
                        if(isset($v['minutes'])){
                            $save['minutes'] = $v['minutes'];
                        }
                        $save['charge_option_id'] = $params['id'];
                        ChargeDetail::create($save);
                    }
                }
            }
            Db::commit();
            return $this->success(['charge_option_id' => $params['id']]);
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->error(code: 1003, msg: $e->getMessage() . $e->getTraceAsString());
        }
    }

    /**
     * 批量选择套餐
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function batchChose(RequestInterface $request): ResponseInterface
    {
        $params = $request->inputs(['charge_id', 'stations']);
        if (!$params['charge_id']) {
            return $this->error(code: '1001', msg: '缺少参数charge_option_id');
        }
        if(!$params['stations']){
            return $this->error(code: '1001', msg: '缺少参数stations');
        }
        if(!is_array($params['stations'])){
            $params['stations'] = json_decode($params['stations']);
        }
        try {
            Station::whereIn('id', $params['stations'])->update(['charge_id' => $params['charge_id']]);
            return $this->success();
        } catch (Exception) {
            return $this->error(1001, '操作繁忙 请稍后重试');
        }
    }

    /**
     * 获取当前已经绑定该套餐的设备
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getChosed(RequestInterface $request): ResponseInterface
    {
        $chargeId = $request->input('charge_id');
        if (!$chargeId) {
            return $this->error(code: '1001', msg: '缺少参数charge_option_id');
        }
        $stations = Station::where('charge_id', $chargeId)
            ->pluck('id')->toArray();
        return $this->success($stations);
    }

    /**
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request): ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if (!$info) {
            return $this->error(code: '400', msg: '登录态失效 请重新登录');
        }
        Db::beginTransaction();
        try {
            $id = $request->input('charge_id', 0);
            if (!$id) {
                return $this->error(ErrorCode::PARAMS_ERR);
            }
           $charge = $this->chargeOption->where('id', $id)
               ->where('distributor_id',$info['id'])
               ->first();
            if (!$charge) {
                return $this->error(code: '1001', msg: '套餐不存在');
            }
            $charge->is_del = 0 ;
            $charge->save();
            ChargeDetail::where('charge_option_id', $id)->update(['is_del' => 0]);
            $now_charge_id = $this->chargeOption->where('distributor_id', 0)
                ->orderBy('sort','desc')->first();
            $chargeId = $now_charge_id->id??0;
            $this->station->where('charge_id', $id)->update(['charge_id' => $chargeId]);
            Db::commit();
            return $this->success();
        } catch (Exception) {
            Db::rollBack();
            return $this->error(code: 1001, msg: '操作繁忙请稍后重试');
        }
    }


    public function setCharge(RequestInterface $request): ResponseInterface
    {
        try {
            $params = $request->inputs(['station_id', 'charge_id']);
            if (!$params['station_id']) {
                return $this->error('1001', '电站id不能为空');
            }
            if (!$params['charge_id']) {
                return $this->error('1001', '套餐信息不能为空');
            }
            $station = $this->station->where('id', $params['station_id'])->first();
            if ($station) {
                $station->charge_id = $params['charge_id'];
                $station->save();
                return $this->success(msg: '修改套餐成功');
            }
            return $this->error('1002', '电站不存在');
        } catch (\Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error($e->getMessage());
        }
    }
}
